#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
更新requirements.txt文件中所有依赖项到最新版本
"""

import subprocess
import re
from pathlib import Path

def get_latest_version(package_name):
    """获取指定包的最新版本号"""
    try:
        cmd = f"pip index versions {package_name}"
        result = subprocess.run(cmd, shell=True, text=True, capture_output=True)
        if result.returncode != 0:
            print(f"警告: 无法获取 {package_name} 的版本信息")
            return None
            
        # 尝试从输出中解析出最新版本号
        output = result.stdout
        latest_match = re.search(r"LATEST:\s+(\d+\.\d+\.\d+[\w\.]*)", output)
        if latest_match:
            return latest_match.group(1)
        
        # 如果上面的方式失败，尝试直接获取第一个版本号
        version_match = re.search(r"Available versions: ([\d\.]+)", output)
        if version_match:
            return version_match.group(1)
            
        print(f"警告: 无法解析 {package_name} 的版本信息")
        return None
    except Exception as e:
        print(f"错误: 获取 {package_name} 版本时出错: {e}")
        return None

def has_special_constraint(line):
    """检查是否有特殊版本约束，如范围限制"""
    # 检查逗号分隔的多个版本约束，如 ">=1.0,<2.0"
    if re.search(r">=\d+\.\d+(\.\d+)?.*,.*[<>=]+\d+\.\d+", line):
        return True
    return False

def update_requirements():
    """更新requirements.txt中的所有依赖到最新版本"""
    requirements_file = Path("requirements.txt")
    
    # 读取当前的requirements文件
    with open(requirements_file, "r", encoding='utf-8') as f:
        lines = f.readlines()
    
    updated_lines = []
    
    for line in lines:
        line = line.strip()
        
        # 跳过空行
        if not line:
            updated_lines.append(line)
            continue
            
        # 保留注释行
        if line.startswith('#'):
            updated_lines.append(line)
            continue
        
        # 检查行内注释
        comment = ""
        if "#" in line:
            package_part, comment = line.split("#", 1)
            line = package_part.strip()
            comment = "  # " + comment.strip()
        
        # 跳过特殊版本约束
        if has_special_constraint(line):
            print(f"保留特殊版本约束: {line}")
            updated_lines.append(line + comment)
            continue
            
        # 解析包名和版本约束
        if ">=" in line or "==" in line:
            package_name = re.split(r">=|==", line)[0].strip()
            
            # 获取最新版本
            latest_version = get_latest_version(package_name)
            
            if latest_version:
                # 构建新的依赖行
                updated_line = f"{package_name}>={latest_version}"
                print(f"更新: {line} -> {updated_line}")
                updated_lines.append(updated_line + comment)
            else:
                print(f"保持不变: {line}")
                updated_lines.append(line + comment)
        else:
            # 对于没有版本约束的行，添加最新版本
            package_name = line.strip()
            
            # 检查是否是实际的包名
            if re.match(r"^[a-zA-Z0-9\._-]+$", package_name):
                latest_version = get_latest_version(package_name)
                if latest_version:
                    updated_line = f"{package_name}>={latest_version}"
                    print(f"添加版本: {line} -> {updated_line}")
                    updated_lines.append(updated_line + comment)
                else:
                    updated_lines.append(line + comment)
            else:
                # 不是有效的包名，保持不变
                updated_lines.append(line + comment)
    
    # 写回更新后的requirements文件
    with open(requirements_file, "w", encoding='utf-8') as f:
        f.write("\n".join(updated_lines))
    
    print(f"\n已更新 {requirements_file} 中的依赖版本")

if __name__ == "__main__":
    update_requirements() 